layui.use(['form', 'table', 'layer', 'upload','xmSelect'], function () {
    var $ = layui.jquery,
        form = layui.form,
        xmSelect = layui.xmSelect,
        upload = layui.upload;

    /** 编辑窗开始 */
    var initData = initArticle();
    var xmSelectInfo = initInfo(form, xmSelect, initData);
    var markDownEditor = initEditor(initData);


    form.on('submit(saveArticleInfoBut)', function (datas) {
        upAddArticleInfo(form, initData, markDownEditor);
    });

    uploadImg(upload);
    /** 编辑窗结束 */

});

function uploadImg(upload){
    upload.render({
        elem: '#imageUpload' //绑定元素
        , url: dl_coder_url.blog_uploadImg[0] //上传接口
        ,
        headers: {"token": headerMap.token},
        field: dl_coder_url.blog_uploadImg[2],
        force: "JSON",
        done: function (result) {
            $('.articleImg').empty();
            $('.articleImg').append('<a href="javascript:void(0);" onclick="openImg();"><input name="articleImg"  id="articleImg" value="' + result.data.img + '" style="display: none;"/> <img  id="showImg" src="' + result.data.imgShow + '" width="200px"></a>');
        }
        , error: function () {
            //请求异常回调
        }
    });
}

/*查看大图*/
function openImg() {
    var idBar = '#showImg';
    var src = $(idBar)[0].src;
    var width = $(idBar).width();
    var height = $(idBar).height();
    var scaleWH = width / height;
    var bigH = 550;
    var bigW = scaleWH * bigH;
    if (bigW > 1000) {
        bigW = 1000;
        bigH = bigW / scaleWH;
    } // 放大预览图片
    parent.layer.open({
        type: 1,
        title: false,
        closeBtn: 1,
        shadeClose: true,
        area: [bigW + 'px', bigH + 'px'], //宽高
        content: '<img width="' + bigW + '" src="' + src + '" />'
    });
}


function upAddArticleInfo(form, initData, markDownEditor) {

    form.render();
    if (!form.validate('.article-edit-add')) {
        return false;
    }

    var formData = $(".article-edit-add").serializeJson();
    formData["articleContent"] = markDownEditor.getPreviewedHTML();
    formData["articleContentMd"] = markDownEditor.getMarkdown();


    var articleContent = formData["articleContent"];
    var articleImg = formData["articleImg"];
    var articleSort = formData["articleSort"];
    var select = formData["select"];
    if (articleContent === null || articleContent === "" || articleContent===undefined ) {
        lay_tishi("文章内容不能为空");
        return false;
    }
    if (articleSort === null || articleSort === "") {
        lay_tishi("文章分类不能为空");
        return false;
    }

    if (select === null || select === "") {
        lay_tishi("文章标签不能为空");
        return false;
    }

    if (articleImg == null || articleImg === "" || articleImg === "null") {
        lay_tishi("文章图片不能为空");
        return false;
    }


    var jsonAuthAjax;
    if (initData !== null && initData !== "") {
        jsonAuthAjax = JSONAuthAjax(dl_coder_url.edit_article[0], dl_coder_url.edit_article[1], formData);
    } else {
        formData["articleEye"] = 0;
        formData["articleStatus"] = 0;
        jsonAuthAjax = JSONAuthAjax(dl_coder_url.add_article[0], dl_coder_url.add_article[1], formData);
    }
    if (jsonAuthAjax.code === http_ok) {
        // 掉用父页面的获取列表方法
        parent.layui.table.reload("blogArticleList");

        // 关闭弹出层
        var iframeIndex = parent.layer.getFrameIndex(window.name);
        parent.layer.close(iframeIndex);
    }
}

function initArticle() {
    var queryString = getQueryString("id");
    if (queryString === null || queryString === '') {
        return null;
    }
    var param = "id=" + queryString;
    var jsonAuthAjax = JSONAuthAjax(dl_coder_url.info_blogArticle[0], dl_coder_url.info_blogArticle[1], param);
    if (jsonAuthAjax.code === http_ok) {
        return jsonAuthAjax.data;
    }

    return null;
}

function initInfo(form, xmSelect, data) {

    var xmSelectInfo;
    //分类下拉
    var articleSort = JSONAuthAjax(dl_coder_url.list_blogSort[0], dl_coder_url.list_blogSort[1]);
    //设置分类单选
    if (articleSort.code === '200') {
        var sortHtml = "";
        for (var i = 0; i < articleSort.data.length; i++) {
            var sortValue = articleSort.data[i];
            sortHtml += '<option value="' + sortValue.id + '" >' + sortValue.sortTitle + '</option>';
        }
        $("#articleSort").append(sortHtml);
    }


    //标签下拉
    var articletag = JSONAuthAjax(dl_coder_url.list_blogTag[0], dl_coder_url.list_blogTag[1]);
    if (articletag.code === '200') {
        //渲染多选
        var jsonAuthAjaxData = articletag.data;
        var selectDataList = [];
        for (var i = 0; i < jsonAuthAjaxData.length; i++) {
            selectDataList.push({'name': jsonAuthAjaxData[i].tagTitle, 'value': jsonAuthAjaxData[i].id});
        }


        //设置多选框
        var splitInit;
        if (data !== null && data.articleTagId) {
            splitInit = data.articleTagId.split(",");
        }
        xmSelectInfo = xmSelect.render({
            el: '#articleCloudTag',
            toolbar: {show: true},
            tips: '选择标签',
            data: selectDataList,
            initValue: splitInit
        });
    }

    //编辑页面信息
    if (data !== null) {
        $(".id").val(data.id);
        $(".articleImgDesc").val(data.articleImgDesc);
        $('.articleImg').empty();
        $('.articleImg').append('<a href="javascript:void(0);" onclick="openImg();"><input name="articleImg"  id="articleImg" value="'+data.img+'" style="display: none;"/> <img  id="showImg" src="' + data.imgShow + '" width="200px"></a>');

        $(".articleTitle").val(data.articleTitle);
        $(".articleDescription").val(data.articleDescription);
        $("#articleSort").val(data.sortId);
    }

    //重新渲染表单,只有执行了这一步，部分表单元素才会自动修饰成功
    layui.form.render('select');
    return xmSelectInfo;
}

// 初始化编辑器
function initEditor(data) {
    // 编辑器名称要与页面中应放置的区域id保持一致
    var markDownEditor = editormd("editArticle", {
        // 高度
        height: 600,
        // 滚动条纵向滚动,设置为false取消滚动
        syncScrolling: "single",
        // lib资源路径
        path: "../../layui-v2.8.0/lay-module/markdown/lib/",
        // 编辑器工具栏区域样式风格
        theme: "default",
        // 编辑器编辑部分样式风格
        editorTheme: "3024-day",
        // 预览区域样式风格
        previewTheme: "dark",
        // 开启表情使用
        emoji: true,
        width: "100%",
        codeFold: true,
        //syncScrolling : false,
        saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
        searchReplace: true,
        htmlDecode: "style,script,iframe|on*",            // 开启 HTML 标签解析，为了安全性，默认不开启
        placeholder: "请输入内容",
        taskList: true,
        tocm: true,         // Using [TOCM]
        toc: true,
        tex: true,                   // 开启科学公式TeX语言支持，默认关闭
        flowChart: true,             // 开启流程图支持，默认关闭
        sequenceDiagram: true,       // 开启时序/序列图支持，默认关闭,
        imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL: dl_coder_url.upload_article_file,
        imageToken: headerMap.token,
        onload: function () {
            if (data !== null) {
                this.setMarkdown(data.articleContentMd);
            }
        }
    });

    return markDownEditor;
}